# coding=UTF-8
# 字符特征提取
from PIL import Image, ImageDraw
import os
import numpy as np
from pylab import *
import cv2 as cv


def batchFeautre(images):
    # 暂时每个字符，花划分5个特征值
    features = np.empty((len(images), 8), dtype='int32')
    for i in range(len(images)):
        features[i][0] = outshape(images[i], "left")
        features[i][1] = outshape(images[i], "right")
        features[i][2] = outshape(images[i], "top")
        features[i][3] = outshape(images[i], "bottom")
        temp = inshape(images[i])
        features[i][4] = temp[0]
        features[i][5] = temp[1]
        features[i][6] = temp[2]
        features[i][7] = temp[3]


# 侧面轮廓深度提取特征
# imarray (numpy对象)
# pos 扫描起点: left 左方，right 右方， top，上方，bottom 下方
def outshape(imarray, pos):
    height = imarray.shape[0]
    width = imarray.shape[1]
    pixcount = 0;
    if (cmp(pos, 'left') == 0):
        for y in range(height):
            for x in range(width):
                if (imarray[y][x] == 0):
                    pixcount = pixcount + x;
                    break;
    elif (cmp(pos, 'right') == 0):
        for y in range(height):
            for x in range(width-1,-1,-1):
                if (imarray[y][x] == 0):
                    pixcount = pixcount + width-x-1;
                    break;
    elif (cmp(pos, 'top') == 0):
        for x in range(width):
            for y in range(height):
                if (imarray[y][x] == 0):
                    pixcount = pixcount + y;
                    break;
    else:
        for x in range(width):
            for y in range(height-1,-1,-1):
                if (imarray[y][x] == 0):
                    pixcount = pixcount + height-y-1;
                    break;

    return pixcount;


# 图像内部网格计算法

def inshape(imarray):
    # 将图片划分为4个网格，分别统计每个网格内内的
    width = imarray.shape[0]
    height = imarray.shape[1]
    top1 = 0
    top2 = 0
    bottom1 = 0
    bottom2 = 0
    for i in range(width):
        for j in range(height):
            if (imarray[i][j] == 0):
                if (i < width / 2 and j < height / 2):
                    top1 = top1 + 1;
                elif (i < width / 2 and j >= height / 2):
                    bottom1 = bottom1 + 1;
                elif (i > width / 2 and j < height / 2):
                    top2 = top2 + 1;
                else:
                    bottom2 = bottom2 + 1;
    return (top1, top2, bottom1, bottom2)
